import React, { useEffect, useState } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { Button, Toast, Empty } from '@nutui/nutui-react';
import { api } from '@/api/api';
import { formatPrice } from '@/utils/formatPrice';
import './detail.less';

const OrderDetailPage = () => {
    const { orderNo } = useParams();
    const navigate = useNavigate();
    const [orderItems, setOrderItems] = useState([]);
    const [orderInfo, setOrderInfo] = useState(null);
    const [loading, setLoading] = useState(false);
    
    const [searchParams] = useSearchParams();
    const orderStatus = searchParams.get('orderStatus');
    const payStatus = searchParams.get('payStatus');

    const getStatusText = () => {
        const status = payStatus || orderStatus || '0';
        switch (status) {
            case '0':
            case 0:
                return '待付款';
            case '1':
            case 1:
                return '已支付';
            case '2':
            case 2:
                return '退款中';
            case '3':
            case 3:
                return '已退款';
            default:
                console.log('getStatusText 默认情况:', status);
                return '待付款';
        }
    };

    const getStatusIcon = () => {
        const status = payStatus || orderStatus || '0';
        
        switch (status) {
            case '0':
            case 0:
                return '⏰';
            case '1':
            case 1:
                return '✓';
            case '2':
            case 2:
                return '🔄';
            case '3':
            case 3:
                return '❌';
            default:
                return '⏰';
        }
    };

    const getStatusDesc = () => {
        const status = payStatus || orderStatus || '0';
        
        switch (status) {
            case '0':
            case 0:
                return '请尽快完成支付，订单将为您保留';
            case '1':
            case 1:
                return '支付成功，订单正在处理中';
            case '2':
            case 2:
                return '退款申请已提交，请耐心等待';
            case '3':
            case 3:
                return '退款已完成，请查收';
            default:
                return '请尽快完成支付，订单将为您保留';
        }
    };
    const getStatusClass = () => {
        const status = payStatus || orderStatus || '0';
        
        switch (status) {
            case '0':
            case 0:
                return 'pending';
            case '1':
            case 1:
                return 'paid';
            case '2':
            case 2:
                return 'refunding';
            case '3':
            case 3:
                return 'refunded';
            default:
                return 'pending';
        }
    };

    // 格式化时间显示
    const formatTime = (timeString) => {
        if (!timeString) return '';
        
        try {
            const date = new Date(timeString);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        } catch (error) {
            return timeString;
        }
    };
    // 获取订单详情
    const fetchOrderDetail = async () => {
        try {
            setLoading(true);
            const response = await api.getOrderItem({
                orderNo: orderNo
            });

            if (response.code === 200) {
                const items = response.data || [];
                setOrderItems(items);
                if (items.length > 0) {
                    const firstItem = items[0];
                    setOrderInfo({
                        orderNo: firstItem.orderNo,
                        createTime: firstItem.createTime,
                        userId: firstItem.userId,
                        shopId: firstItem.shopId,
                        orderStatus: firstItem.orderStatus,
                        payStatus: firstItem.payStatus,
                        totalAmount: items.reduce((sum, item) => sum + (item.subtotal || 0), 0),
                        totalQuantity: items.reduce((sum, item) => sum + (item.quantity || 0), 0)
                    });
                }
            }
        } catch (error) {
            console.error('获取订单详情失败:', error);
            Toast.show('获取订单详情失败');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (orderNo) {
            fetchOrderDetail();
        }
    }, [orderNo]);

    return (
        <div className="order-detail-page">
         
            
            <div className="order-detail-content">
                {loading ? (
                    <div className="loading-container">
                        <div className="loading-spinner"></div>
                        <span>加载中...</span>
                    </div>
                ) : orderItems.length > 0 ? (
                    <>
                        <div className={`order-status-card status-${getStatusClass()}`}>
                            <div className="status-icon">{getStatusIcon()}</div>
                            <div className="status-info">
                                <div className="status-text">{getStatusText()}</div>
                                <div className="status-desc">{getStatusDesc()}</div>
                            </div>
                        </div>

                        <div className="order-info-section">
                            <div className="section-title">订单信息</div>
                            <div className="info-grid">
                                <div className="info-item">
                                    <span className="info-label">订单号</span>
                                    <span className="info-value">{orderInfo?.orderNo}</span>
                                </div>
                                <div className="info-item">
                                    <span className="info-label">下单时间</span>
                                    <span className="info-value">{formatTime(orderInfo?.createTime)}</span>
                                </div>
                                <div className="info-item">
                                    <span className="info-label">商品数量</span>
                                    <span className="info-value">{orderInfo?.totalQuantity} 件</span>
                                </div>
                                <div className="info-item">
                                    <span className="info-label">订单金额</span>
                                    <span className="info-value amount">{formatPrice(orderInfo?.totalAmount)}</span>
                                </div>
                            </div>
                        </div>

                        {/* 商品清单 */}
                        <div className="order-items-section">
                            <div className="section-title">
                                <span>商品清单</span>
                                <span className="item-count">共 {orderItems.length} 件</span>
                            </div>
                            <div className="items-container">
                                {orderItems.map((item, index) => (
                                    <div key={index} className="order-item">
                                        <div className="item-image">
                                            <img 
                                                src={item.productImg || item.productImage} 
                                                alt={item.productName}
                                                onError={(e) => {
                                                    e.target.src = 'https://via.placeholder.com/80x80?text=No+Image';
                                                }}
                                            />
                                        </div>
                                        <div className="item-details">
                                            <div className="item-name">{item.productName}</div>
                                            <div className="item-spec">
                                                {item.specJson ? JSON.parse(item.specJson).name : '默认规格'}
                                            </div>
                                            <div className="item-price-quantity">
                                                <span className="item-price">{formatPrice(item.unitPrice)}</span>
                                                <span className="item-quantity">×{item.quantity}</span>
                                            </div>
                                        </div>
                                        <div className="item-subtotal">
                                            {formatPrice(item.subtotal)}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>

                        {/* 订单统计 */}
                        <div className="order-summary">
                            <div className="summary-row">
                                <span className="summary-label">商品总价</span>
                                <span className="summary-value">{formatPrice(orderInfo?.totalAmount)}</span>
                            </div>
                            <div className="summary-row">
                                <span className="summary-label">运费</span>
                                <span className="summary-value">¥0.00</span>
                            </div>
                            <div className="summary-row total">
                                <span className="summary-label">实付金额</span>
                                <span className="summary-value">{formatPrice(orderInfo?.totalAmount)}</span>
                            </div>
                        </div>
                    </>
                ) : (
                    <Empty description="暂无订单详情" />
                )}
            </div>
        </div>
    );
};

export default OrderDetailPage;